const express = require("express");
const { Server } = require("@tus/server");
const { FileStore } = require("@tus/file-store");
const app = express();
const uploadApp = express();
const PORT = process.env.PORT || 3333;
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded());
app.use(express.static("public"));

/*app.use((req, res, next) => {
  if(req.path !== '/' && !req.path.includes('.')){
    res.set({
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Allow-Origin': req.headers.origin || '*',
      'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
      'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
      'Content-Type': 'application/json; charset=utf-8'
    })
  }
  req.method === 'OPTIONS' ? res.status(204).end() : next()
})*/

const tusServer = new Server({
  path: "/files",
  datastore: new FileStore({ directory: "./files" }),
});

app.get("/test", (req, res) => {
  res.status(200).end("abc");
});
uploadApp.all("*", tusServer.handle.bind(tusServer));
app.use("/files", uploadApp);

app.listen(PORT, function () {
  console.log("Listen at http://localhost:" + PORT);
});
